# This file is part of trytond-pcw-production module for Tryton. 
# The COPYRIGHT file at the top level of this repository contains 
# the full copyright notices and license terms.

from trytond.model import ModelSingleton, Workflow, ModelView, ModelSQL, fields
from trytond.wizard import Wizard, StateView, Button, StateTransition
from trytond.pyson import If, Eval, Bool, Or, And, Not, Equal
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
from decimal import Decimal

__all__ = ['ProductionOrderTmpl',
           'ProductionOrderRawTmpl', 
           'ProductionOrderFinishTmpl',
           'ProductionTemplateWizard',
           'ProductionCreateStart']
__metaclass__ = PoolMeta

class ProductionOrderTmpl(ModelSQL, ModelView):
    "Pcw Production Order Template"
    __name__ = 'pcw.production.order.tmpl'

    name = fields.Char('Name', size=None, select=True, required=True)
    order_raw_tmpl_line = fields.One2Many('pcw.production.order.raw.tmpl', 'tmpl', 'Template Raw Order Lines')
    order_finish_tmpl_line = fields.One2Many('pcw.production.order.finish.tmpl', 'tmpl', 'Template Finish Order Lines')
    company = fields.Many2One('company.company', 'Company', select=True)
    notes = fields.Text('Notes')

class ProductionOrderRawTmpl(ModelSQL, ModelView):
    "Pcw Production Order Raw Template Line"
    __name__ = 'pcw.production.order.raw.tmpl'

    tmpl = fields.Many2One('pcw.production.order.tmpl', 'Production Order Template', ondelete='CASCADE', select=True, required=True)
    product = fields.Many2One('product.product', 'Product',
        domain=[('type', '!=', 'service')],
        on_change=['product'], required=True)
    uom = fields.Many2One('product.uom', 'Unit',
        states={
            'required': Bool(Eval('product')),
            },
        domain=[
            If(Bool(Eval('product_uom_category')),
                ('category', '=', Eval('product_uom_category')),
                ('category', '!=', -1)),
            ])
    quantity = fields.Float('Quantity', digits=(16, 4),
        states={
            'required': Bool(Eval('product')),
            })
    product_uom_category = fields.Function(
        fields.Many2One('product.uom.category', 'Product Uom Category',
            on_change_with=['product']), 'on_change_with_product_uom_category')

    @staticmethod
    def default_quantity():
        return 1

    def on_change_with_product_uom_category(self, name=None):
        if self.product:
            return self.product.default_uom_category.id

    def on_change_product(self):
        res = {}
        res['quantity'] = 1.0
        if not self.product:
            res['uom'] = None
            return res
        res['uom'] = self.product.default_uom.id
        return res

class ProductionOrderFinishTmpl(ModelSQL, ModelView):
    "Pcw Production Order Finish Line Template"
    __name__ = 'pcw.production.order.finish.tmpl'

    tmpl = fields.Many2One('pcw.production.order.tmpl', 'Production Order Template', ondelete='CASCADE', select=True, required=True)
    product = fields.Many2One('product.product', 'Product',
        domain=[('type', '!=', 'service')],
        on_change=['product'], required=True)
    uom = fields.Many2One('product.uom', 'Unit',
        states={
            'required': Bool(Eval('product')),
            },
        domain=[
            If(Bool(Eval('product_uom_category')),
                ('category', '=', Eval('product_uom_category')),
                ('category', '!=', -1)),
            ])
    product_uom_category = fields.Function(
        fields.Many2One('product.uom.category', 'Product Uom Category',
            on_change_with=['product']), 'on_change_with_product_uom_category')
    quantity = fields.Float('Quantity', digits=(16, 4),
        states={
            'required': Bool(Eval('product')),
            })

    @staticmethod
    def default_quantity():
        return 1

    def on_change_with_product_uom_category(self, name=None):
        if self.product:
            return self.product.default_uom_category.id

    def on_change_product(self):
        res = {}
        res['quantity'] = 1.0
        if not self.product:
            res['uom'] = None
            return res
        res['uom'] = self.product.default_uom.id
        return res

class ProductionTemplateWizard(Wizard):
    __name__ = "pcw.production.create" 

    start = StateView('pcw.production.create.start',
        'pcw_production.pcw_production_tmpl_create_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Create', 'create_', 'tryton-ok', default=True),
            ])
    create_ = StateTransition()

    def transition_create_(self):
        Order = Pool().get('pcw.production.order')
        Raw = Pool().get('pcw.production.order.raw')
        Finish = Pool().get('pcw.production.order.finish')
        Company = Pool().get('company.company')

        company = Company(Transaction().context.get('company'))

        order = Order()
        order.date = self.start.date
        order.reference = self.start.template.name 
        order.save()

        for det in self.start.template.order_raw_tmpl_line:
            raw = Raw()
            raw.order = order.id
            raw.product = det.product
            raw.uom = det.uom
            raw.waste_uom = det.uom
            raw.quantity = det.quantity
            pcw_cost = Decimal('%.4f' % det.product.get_average_cost(det.uom))
            raw.suggested_cost = pcw_cost
            raw.unit_price = pcw_cost
            raw.save()

        for det in self.start.template.order_finish_tmpl_line:
            finish = Finish()
            finish.order = order.id
            finish.product = det.product
            finish.uom = det.uom
            finish.quantity = det.quantity
            pcw_cost = Decimal('%.4f' % det.product.get_last_cost(det.uom))
            finish.suggested_cost = pcw_cost
            finish.unit_price = pcw_cost
            finish.save()

        return 'end'

class ProductionCreateStart(ModelView):
    "Creates Pcw Order Production"
    __name__ = 'pcw.production.create.start'
    date = fields.Date('Date', required=True)
    template = fields.Many2One('pcw.production.order.tmpl',
            'Production template', required=True)

